//用户界面的js
//JavaScript代码区域
layui.use(['element', 'form', 'jquery', 'layer', 'table', 'upload'], function () {
    var element = layui.element;
    var form = layui.form;
    var $ = layui.jquery;
    var table = layui.table;
    var layer = layui.layer;
    var upload = layui.upload;

    //商家列表显示
    var tableData = table.render({
        elem: '#communities'
        , url: '/system/community/loadAllCommunities'
        , page: true //开启分页
        , toolbar: true //开启头部工具栏，并为其绑定左侧模板
        , title: '商家数据表'
        , limits: [10, 20, 50, 100]
        , cols: [ [
            {field: 'communityId', title: '小区编号', sort: true, align: 'center'}
            , {field: 'communityName', title: '小区名称', align: 'center'}
            , {field: 'communityPhone', title: '联系方式', align: 'center'}
            , {field: 'areaAddress', title: '区域地址', align: 'center'}
            , {field: 'detailedAddress', title: '详细地址', align: 'center'}
            , {field: 'longitude', title: '经度', align: 'center'}
            , {field: 'latitude', title: '纬度', align: 'center'}
            , {field: 'communityPic', title: '商家外观', align: 'center', templet : function (d) {
                    var str = d.communityPic;
                    var arr = str.split(",");
                    return '<img style="width: 50px;" src='+arr[0]+'>';
                }}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', align: 'center'}
        ] ]
    });

    //商家图片多文件上传
    //定义文件队列
    let files;
    var uploadCommunityPic = upload.render({
        elem: '#bindViewPic', //绑定元素
        multiple: true,
        auto: false,
        acceptMime: 'image/*',
        bindAction: "#bindAddPic",//绑定上传
        url: '/system/community/file/uploadCommunityPic', //上传接口
        choose: function (obj) { //obj参数包含的信息，跟 choose回调完全一致
            //将每次选择的文件追加到文件队列
            files = obj.pushFile();
            //layer.load(); //上传loading
            obj.preview(function (index, file, result) {
                //该节点是删除预览图片的
                $("#forRemoveNode").append('<img src="' + result + '" id="remove_' +
                    index + '" title="双击删除该图片" style="width:100px;height:100px;margin: 15px;">');
                //双击删除指定预上传图片,dblclick为双击事件
                $('#remove_' + index).bind('dblclick', function () {
                    delete files[index];//删除指定图片
                    $(this).remove();
                })
            })
        },
        done: function (res) {
            //获取回调的文件地址
            var path = res.path;
            //清空预览图,清空预览图片节点下的所有图片
            var forRemove = document.getElementById("forRemoveNode");
            while(forRemove.hasChildNodes()){
                forRemove.removeChild(forRemove.firstChild);
            }
            //关闭提交按钮
            $('#bindAddPic').attr("disable","true");
            $('#bindAddPic').addClass("layui-btn-disabled");
            //在节点下添加回调的图片
            $('#forUploadNode').append('<img src="/system/community/file/showPicByPath?path='+ path +'" class="layui-upload-img" style="width:100px;height:100px;margin: 15px;">');
            //判断隐藏域内的val是否为默认图片,若是,则清除隐藏域里的默认路径
            if ($('#a_communityPicInput').val() == "default/default.jpg"){
                $('#a_communityPicInput').val("");
            }
            //拼接字符串
            var str = $('#a_communityPicInput').val();
            if  (str == "" || str == null){
                $('#a_communityPicInput').val(path);
            } else {
                $('#a_communityPicInput').val(str+","+path);
            }
            //上传完毕回调
            //调用清空文件队列函数
            clearFile();
        },
        error: function () {
            //请求异常回调
        }
    });

    //清空文件队列函数
    function clearFile(){
        for (let x in files) {
            delete files[x];
        }
    }

    //编辑弹出层的商家图片上传以及删除
    //定义文件队列
    let newUploadFiles;
    var uploadCommunityPic = upload.render({
        elem: '#e_bindViewPic', //绑定元素
        multiple: true,
        auto: false,
        acceptMime: 'image/*',
        bindAction: "#bindEditPic",//绑定上传
        url: '/system/community/file/uploadCommunityPic', //上传接口
        choose: function (obj) { //obj参数包含的信息，跟 choose回调完全一致
            //将每次选择的文件追加到文件队列
            newUploadFiles = obj.pushFile();
            //layer.load(); //上传loading
            obj.preview(function (index, file, result) {
                //该节点是删除预览图片的
                $("#beforeUploadPics").append('<img src="' + result + '" id="remove_' +
                    index + '" title="双击删除该图片" style="width:100px;height:100px;margin: 15px;">');
                //双击删除指定预上传图片,dblclick为双击事件
                $('#remove_' + index).bind('dblclick', function () {
                    delete newUploadFiles[index];//删除指定图片
                    $(this).remove();
                })
            })
        },
        done: function (res) {
            //获取回调的文件地址
            var path = res.path;
            //清空新上传前的预览图,清空预览图片节点下的所有图片
            var beforePics = document.getElementById("beforeUploadPics");
            while(beforePics.hasChildNodes()){
                beforePics.removeChild(beforePics.firstChild);
            }
            //关闭提交按钮
            $('#bindEditPic').attr("disable","true");
            $('#bindEditPic').addClass("layui-btn-disabled");
            //在节点下添加回调的图片
            $('#afterUploadPics').append('<img src="/system/community/file/showPicByPath?path='+ path +'" class="layui-upload-img" style="width:100px;height:100px;margin: 15px;">');
            /*//判断隐藏域内的val是否为默认图片,若是,则清除隐藏域里的默认路径
            if ($('#e_communityPicInput').val() == "default/default.jpg"){
                $('#e_communityPicInput').val("");
            }
            //拼接字符串
            var str = $('#e_communityPicInput').val();
            if  (str == "" || str == null){
                $('#e_communityPicInput').val(path);
            } else {
                $('#e_communityPicInput').val(str+","+path);
            }
            //上传完毕回调*/
            //先清空输入框内的value值
            /*$('#e_communityPicInput').val("");
            var str = "";*/
            $("#displayPics").each(function() {
                var src = $(this).attr("src");
                console.log(src)
            });

            //调用清空编辑商家图片上传文件队列函数
            clearNewUploadFile()
        },
        error: function () {
            //请求异常回调
        }
    });

    //清空编辑商家图片上传文件队列函数
    function clearNewUploadFile(){
        for (let x in newUploadFiles) {
            delete newUploadFiles[x];
        }
    }

    //获取弹出层的索引
    var addIndex;
    //添加商家弹出层
    $('#doAdd').click(function () {
        addIndex = layer.open({
            type: 1,
            title: '添加商家',
            //content属性为打开某个定义好的
            content: $('#addCommunityDiv'),
            area: ['800px', '700px'],
            //这个函数是防止打开弹窗后遮挡屏幕
            success: function (layer) {
                var mask = $(".layui-layer-shade");
                mask.appendTo(layer.parent());
                //其中：layer是弹层的DOM对象
                //每次打开弹出层时刷新内容
                $('#reloadFrame').click();
                //打开弹出层时清空预览图,清空预览图片节点下的所有图片
                var forRemove = document.getElementById("forRemoveNode");
                while(forRemove.hasChildNodes()){
                    forRemove.removeChild(forRemove.firstChild);
                }
                //打开提交按钮
                $('#bindAddPic').attr("disable","false");
                $('#bindAddPic').removeClass("layui-btn-disabled");
                //打开时清空已经上传的图片
                var forUpload = document.getElementById("forUploadNode");
                while(forUpload.hasChildNodes()){
                    forUpload.removeChild(forUpload.firstChild);
                }
                //打开时为隐藏域赋值
                $('#a_communityPicInput').val("default/default.jpg");
            }
        })
    });
    //添加商家事件结束


    //监控提交事件
    form.on("submit(doSubmit)", function (data) {
        $.post('/system/community/addCommunity', data.field, function (res) {
            if (res.code == 200) {
                layer.confirm('是否继续录入？', {
                    btn: ['继续', '取消'] //按钮
                }, function (myself) {
                    //打开弹出层时清空预览图,清空预览图片节点下的所有图片
                    var forRemove = document.getElementById("forRemoveNode");
                    while(forRemove.hasChildNodes()){
                        forRemove.removeChild(forRemove.firstChild);
                    }
                    //打开时清空已经上传的图片
                    var forUpload = document.getElementById("forUploadNode");
                    while(forUpload.hasChildNodes()){
                        forUpload.removeChild(forUpload.firstChild);
                    }
                    //打开时为隐藏域添加默认图片
                    $('#a_communityPicInput').val("default/default.jpg");
                    //打开提交按钮
                    $('#bindAddPic').attr("disable","false");
                    $('#bindAddPic').removeClass("layui-btn-disabled");
                    //无论继续输入还是取消重置按钮会被点击
                    $('#reloadFrame').click();
                    layer.close(myself);
                }, function () {
                    //打开弹出层时清空预览图,清空预览图片节点下的所有图片
                    var forRemove = document.getElementById("forRemoveNode");
                    while(forRemove.hasChildNodes()){
                        forRemove.removeChild(forRemove.firstChild);
                    }
                    //打开时清空已经上传的图片
                    var forUpload = document.getElementById("forUploadNode");
                    while(forUpload.hasChildNodes()){
                        forUpload.removeChild(forUpload.firstChild);
                    }
                    //打开时为隐藏域添加默认图片
                    $('#a_communityPicInput').val("default/default.jpg");
                    //无论继续输入还是取消重置按钮会被点击
                    $('#reloadFrame').click();
                    //打开提交按钮
                    $('#bindAddPic').attr("disable","false");
                    $('#bindAddPic').removeClass("layui-btn-disabled");
                    layer.close(addIndex);
                });
            }
            //不管成功还是失败,父级页面都要刷新
            tableData.reload();
        });
        //要应用ajax提交,所以return false
        return false;
    });
    //提交事件结束

    //执行查询
    form.on("submit(doSearch)", function (data) {
        tableData.reload({
            url: '/system/community/loadAllCommunities',
            //where是将条件拼接在后面
            where: data.field
        })
        //返回数据时自动将输入框清空
        $('#communityName').val("");
        $('#communityPhone').val("");
        $('#detailedAddress').val("");
        //防止提交
        return false;
    })
    //查询事件结束

    //监听工具条的事件
    table.on('tool(communityTable)', function (obj) {
        //userTable是数据表格中lay-filter对应的事件
        var event = obj.event;
        var communityData = obj.data;
        switch (event) {
            //通过id删除用户
            case 'deleteCommunityById':
                layer.confirm("确认删除 ID为 " + communityData.communityId + " 这条数据吗?", function () {
                    $.post('/system/community/deleteCommunityById', communityData, function (res) {
                        if (res.code == 200) {
                            //无论删除成功还是失败都刷新表格
                            tableData.reload();
                            layer.msg(res.msg);
                        } else if (res.code == -1) {
                            //无论删除成功还是失败都刷新表格
                            tableData.reload();
                            layer.msg(res.msg);
                        }
                    })
                });
                break;
            //删除事件结束

            //修改事件开始
            case 'editCommunityById':
                //获取修改用户弹出层的索引
                var editIndex;
                //修改用户弹出层
                editIndex = layer.open({
                    type: 1,
                    title: '修改商家',
                    //content属性为打开某个定义好的
                    content: $('#editCommunityDiv'),
                    area: ['800px', '700px'],
                    success: function (layer) {
                        //防止打开弹窗后遮挡屏幕
                        var mask = $(".layui-layer-shade");
                        mask.appendTo(layer.parent());
                        //其中：layer是弹层的DOM对象
                        form.val('formData', communityData);
                        //打开清空上个弹出层的图片,清空预览图片节点下的所有图片
                        var displayPics = document.getElementById("displayPics");
                        while(displayPics.hasChildNodes()){
                            displayPics.removeChild(displayPics.firstChild);
                        }
                        var imageUrls = communityData.communityPic;
                        var urls = imageUrls.split(",");
                        var str = "";
                        for (var i = 0; i < urls.length; i++) {
                            //console.log(urls[i]);
                            $('#displayPics').append('<img id="communityPic_'+i+'" title="双击删除该图片" src="'+ urls[i] +'" class="layui-upload-img" style="width:100px;height:100px;margin: 10px;">')
                            //双击删除指定图片,dblclick为双击事件
                            $('#communityPic_' + i).bind('dblclick', function () {
                                $('#editAvatarUrlInput').val("");
                                //delete files[index];//删除指定图片
                                $(this).remove();
                            })
                        }
                    }
                });


                //监听修改事件
                form.on('submit(editSubmit)', function (communityData) {
                    layer.confirm("确认修改吗?", function () {
                        $.post('/system/community/editCommunity', communityData.field, function (res) {
                            if (res.code == 200) {
                                //无论修改成功还是失败都刷新表格
                                layer.close(editIndex);
                                tableData.reload();
                                layer.msg(res.msg);
                            } else if (res.code == -1) {
                                //无论删除成功还是失败都刷新表格
                                layer.close(editIndex);
                                tableData.reload();
                                layer.msg(res.msg);
                            }
                        })
                    })
                    //console.log(userData.field);
                    return false;
                })
                break;
            //修改用户事件结束
        }
    })


});